class Teacher < ActiveRecord::Base
  include HTTParty
  base_uri 'www.jagajx.com'
  #debug_output $stdout

  attr_accessor :phone, :name, :url, :cookie, :last_docs

  def initialize(url, name, phone, cookie)
    @phone = phone
    @name = name
    @url = url.gsub('pxbc=1', 'pxbc=0').gsub('pxbc=3', 'pxbc=0').gsub('pxbc=5', 'pxbc=0').gsub('pxbc=9', 'pxbc=0')
    @cookie = cookie
    @last_docs = []
  end

  def morning_points
    points_doc coaches_url 0
  end

  def afternoon_points
    points_doc coaches_url 2
  end

  def evening_points
    points_doc coaches_url 4
    #/html/body/table[3]/tbody/tr[3]/td/table[1]
  end

  def coaches_url(pxbc)
    @url.gsub('pxbc=0', "pxbc=#{pxbc}").gsub('pfs/dr_coaches', 'pfs/dr_coaches/CDefault')
  end

  def points_page(url)
    self.class.get(url, headers: {'Cookie' => @cookie})
  end

  def points_doc(url)
    resp = points_page(url)
    doc = Nokogiri::HTML(resp.body)
    @last_docs = doc.css('table table')[0].css('td a')
    @last_docs.map { |doc| Point.new(doc.to_s, @url, @cookie) }
  end

  def to_s
    "#{name}(#{phone})"
  end
end
